<template>
  <div class="order-detail-container">
    <div class="back-button">
      <el-button @click="goBack" icon="el-icon-arrow-left">返回订单列表</el-button>
    </div>
    
    <el-row :gutter="20" v-if="order">
      <el-col :span="16">
        <el-card class="order-info">
          <template #header>
            <div class="card-header">
              <span>订单详情</span>
              <el-tag :type="order.status === 0 ? 'warning' : 'success'" size="large">
                {{ order.status === 0 ? '进行中' : '已完成' }}
              </el-tag>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单编号">{{ order.id }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ formatDate(order.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="租车时间">
              {{ formatDate(order.startTime) }} 至 {{ formatDate(order.endTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="总价">
              <span class="price">¥ {{ order.totalPrice }}</span>
            </el-descriptions-item>
          </el-descriptions>
          
          <el-divider>车辆信息</el-divider>
          
          <div class="vehicle-info" v-if="vehicle">
            <div class="vehicle-image">
              <img :src="getImageUrl(vehicle.imageUrl)" alt="车辆图片" @error="handleImageError">
            </div>
            <div class="vehicle-details">
              <h3>{{ vehicle.brand }} {{ vehicle.model }}</h3>
              <p>车牌号：{{ vehicle.plateNumber }}</p>
              <p>颜色：{{ vehicle.color }}</p>
              <p>座位数：{{ vehicle.seatCount }}座</p>
              <p>日租价格：¥ {{ vehicle.dailyPrice }}</p>
            </div>
          </div>
          <el-empty v-else description="车辆信息加载中..."></el-empty>
          
          <el-divider>车行信息</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="box-card">
                <template #header>
                  <div class="card-header">
                    <span>取车地点</span>
                  </div>
                </template>
                <div>
                  <p>车行名称：{{ startShopName }}</p>
                  <p>地址：{{ startShopAddress || '北京市' }}</p>
                  <p>联系电话：{{ startShopPhone || '010-12345678' }}</p>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="box-card">
                <template #header>
                  <div class="card-header">
                    <span>还车地点</span>
                  </div>
                </template>
                <div>
                  <p>车行名称：{{ endShopName }}</p>
                  <p>地址：{{ endShopAddress || '上海市' }}</p>
                  <p>联系电话：{{ endShopPhone || '021-12345678' }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <div class="action-buttons" v-if="order.status === 0">            
            <el-button type="success" @click="goToReturnVehicle">归还车辆</el-button>            
            <el-button type="primary" @click="completeOrder">完成订单</el-button>            
            <el-button type="danger" @click="cancelOrder">取消订单</el-button>          
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="evaluation-card" v-if="order.status === 1">
          <template #header>
            <div class="card-header">
              <span>评价信息</span>
            </div>
          </template>
          
          <div v-if="evaluation">
            <el-rate v-model="evaluation.score" disabled show-score></el-rate>
            <p class="evaluation-content">{{ evaluation.content }}</p>
            <p class="evaluation-time">评价时间：{{ formatDate(evaluation.createTime) }}</p>
          </div>
          <div v-else class="no-evaluation">
            <el-empty description="暂无评价">
              <template #description>
                <p>您还没有评价该订单</p>
              </template>
              <el-button type="primary" @click="showEvaluationDialog">立即评价</el-button>
            </el-empty>
          </div>
        </el-card>
        
        <el-card class="help-card">
          <template #header>
            <div class="card-header">
              <span>订单帮助</span>
            </div>
          </template>
          
          <div class="help-content">
            <p><i class="el-icon-info"></i> 如遇车辆问题，请拨打客服电话：400-123-4567</p>
            <p><i class="el-icon-warning"></i> 异地还车可能产生额外费用</p>
            <p><i class="el-icon-time"></i> 超时将额外计费，请按时还车</p>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-empty v-else description="加载中..." :image-size="200"></el-empty>
    
    <!-- 评价对话框 -->
    <el-dialog title="评价订单" v-model="evaluationDialogVisible" width="500px">
      <el-form :model="evaluationForm" label-width="100px">
        <el-form-item label="评分">
          <el-rate v-model="evaluationForm.score" :max="5" show-score></el-rate>
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input type="textarea" v-model="evaluationForm.content" rows="4" placeholder="请输入您的评价内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="evaluationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEvaluation">提交评价</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderDetail, completeOrder as apiCompleteOrder, cancelOrder as apiCancelOrder } from '@/api/order'
import { getVehicleDetail } from '@/api/vehicle'
import * as apiSubmitEvaluation from '@/api/evaluation'

const route = useRoute()
const router = useRouter()
const order = ref(null)
const vehicle = ref(null)
const evaluation = ref(null)
const startShopName = ref('取车车行')
const startShopAddress = ref('')
const startShopPhone = ref('')
const endShopName = ref('还车车行')
const endShopAddress = ref('')
const endShopPhone = ref('')
const evaluationDialogVisible = ref(false)
const evaluationForm = reactive({
  score: 5,
  content: ''
})

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    const orderId = route.params.id
    if (!orderId) {
      ElMessage.error('无效的订单ID')
      router.push('/order/list')
      return
    }
    
    const res = await getOrderDetail(orderId)
    order.value = res.data
    
    // 获取相关信息
    if (order.value) {
      fetchVehicleInfo()
      fetchShopInfo()
      fetchEvaluationInfo()
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 获取车辆信息
const fetchVehicleInfo = async () => {
  try {
    const res = await getVehicleDetail(order.value.vehicleId)
    vehicle.value = res.data
  } catch (error) {
    console.error('获取车辆信息失败:', error)
  }
}

// 获取车行信息
const fetchShopInfo = async () => {
  // 这里应调用车行服务API
  // 模拟数据
  startShopName.value = `取车车行ID: ${order.value.startShopId}`
  endShopName.value = `还车车行ID: ${order.value.endShopId}`
}

// 获取评价信息
const fetchEvaluationInfo = async () => {
  try {
    // 获取订单评价
    const res = await apiSubmitEvaluation.getOrderEvaluation(order.value.id);
    if (res.data && res.data.success) {
      evaluation.value = res.data.data;
    } else {
      evaluation.value = null; // 暂无评价
    }
  } catch (error) {
    console.error('获取评价信息失败:', error);
    evaluation.value = null;
  }
}

// 返回订单列表
const goBack = () => {
  router.push('/order/list')
}

// 完成订单
const completeOrder = () => {
  ElMessageBox.confirm('确定要完成该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      await apiCompleteOrder(order.value.id)
      ElMessage.success('订单已完成')
      fetchOrderDetail() // 刷新数据
    } catch (error) {
      console.error('完成订单失败:', error)
      ElMessage.error('完成订单失败')
    }
  }).catch(() => {})
}

// 跳转到车辆归还页面
const goToReturnVehicle = () => {  
  router.push(`/order/${order.value.id}/return`)
}
// 取消订单
const cancelOrder = () => {  
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {    
    confirmButtonText: '确定',    
    cancelButtonText: '取消',    
    type: 'warning'  
  }).then(async () => {    
    try {      
      await apiCancelOrder(order.value.id)      
      ElMessage.success('订单已取消')      
      router.push('/order/list')    
    } catch (error) {      
      console.error('取消订单失败:', error)      
      ElMessage.error('取消订单失败')    
    }  }).catch(() => {})
  }

// 显示评价对话框
const showEvaluationDialog = () => {
  evaluationForm.score = 5
  evaluationForm.content = ''
  evaluationDialogVisible.value = true
}

// 提交评价
const submitEvaluation = async () => {
  try {
    const evaluationData = {
      orderId: order.value.id,
      userId: Number(localStorage.getItem('userId') || 0),
      shopId: order.value.startShopId, // 使用取车车行的ID作为评价的车行
      score: evaluationForm.score,
      content: evaluationForm.content
    };
    
    // 调用API提交评价
    const res = await apiSubmitEvaluation.submitEvaluation(evaluationData);
    
    if (res.data && res.data.success) {
      ElMessage.success('评价提交成功');
      evaluationDialogVisible.value = false;
      
      // 刷新评价信息
      fetchEvaluationInfo();
    } else {
      ElMessage.error(res.data?.message || '评价提交失败');
    }
  } catch (error) {
    console.error('评价提交失败:', error);
    ElMessage.error('评价提交失败');
  }
}

// 图片URL处理函数
const getImageUrl = (url) => {
  if (!url) return '/assets/no-image.png';
  
  // 如果是绝对URL（以http开头），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    // 如果是placeholder站点且有连接问题，使用本地占位图
    if (url.includes('via.placeholder.com')) {
      return '/assets/no-image.png';
    }
    return url;
  }
  
  // 如果是相对URL，需要检查格式并调整
  
  // 1. 修正端口问题：从3000改为8081
  if (url.includes('localhost:3000')) {
    url = url.replace('localhost:3000', 'localhost:8081');
  }
  
  // 2. 如果URL不以/开头，添加/
  if (!url.startsWith('/')) {
    url = '/' + url;
  }
  
  // 拼接服务器地址，使用正确的端口8081
  const host = window.location.protocol + '//' + window.location.hostname + ':8081';
  return host + url;
}

// 图片加载错误处理
const handleImageError = (e) => {
  if (e && e.target) {
    // 使用本地资源文件夹中的占位图
    e.target.src = '/assets/no-image.png';
  }
}

// 组件挂载时获取订单详情
onMounted(() => {  
  fetchOrderDetail()
})
// 导出方法
// return {
//   order,
//   vehicle,
//   evaluation,
//   startShopName,
//   endShopName,
//   startShopAddress,
//   endShopAddress,
//   startShopPhone,
//   endShopPhone,
//   evaluationForm,
//   evaluationDialogVisible,
//   formatDate,
//   getImageUrl,
//   handleImageError,
//   goBack,
//   completeOrder,
//   cancelOrder,
//   goToReturnVehicle,
//   showEvaluationDialog,
//   submitEvaluation
//   }
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 20px;
}

.vehicle-info {
  display: flex;
  gap: 20px;
  margin: 20px 0;
}

.vehicle-image {
  width: 300px;
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
}

.vehicle-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.vehicle-details h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.vehicle-details p {
  margin: 5px 0;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.evaluation-card, .help-card {
  margin-bottom: 20px;
}

.evaluation-content {
  margin: 15px 0;
  line-height: 1.5;
}

.evaluation-time {
  color: #999;
  font-size: 14px;
}

.no-evaluation {
  padding: 20px 0;
}

.help-content {
  line-height: 1.8;
}

.help-content p {
  margin: 10px 0;
}
</style> 